package com.ycl.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ycl.common.Result;
import com.ycl.entity.User;
import com.ycl.service.UserService;
import com.ycl.utils.SMSUtils;
import com.ycl.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 发送手机短信验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public Result<String> sendMsg(@RequestBody User user, HttpSession session){
        // 获取手机号
        String phone = user.getPhone();

        if (Strings.isNotEmpty(phone)){
            // 随机生成4为验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code:{}",code);

            // 调用阿里云提供的短信验证服务
//            SMSUtils.sendMessage("这是签名","这是模板ID",phone,code);

            // 将生成的code验证码存到session
//            session.setAttribute(phone,code);

            // 将生成的验证码保存到redis中,并设置有效期为五分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

            return Result.success("验证码发送成功");
        }
        return Result.error("验证码发送失败");
    }

    @PostMapping("/login")
    public Result<User> login(@RequestBody Map<String,String> map,HttpSession session){
        log.info(map.toString());
        // 获取手机号
        String phone = map.get("phone");
        // 获取验证码
        String code = map.get("code");
        // 从Session中获取验证码
//        String codeInSession = session.getAttribute(phone).toString();
        // 从redis中获取缓存的验证码
        String codeInSession = (String) redisTemplate.opsForValue().get(phone);

        // 进行验证码比对
        if (codeInSession != null && codeInSession.equals(code)){
            // 比对成功
            // 判断当前手机号是否为新用户，如果是新用户则进行注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());

            // 如果用户登录成功删除redis中缓存的验证码
            redisTemplate.delete(phone);
            return Result.success(user);
        }

        // 比对失败
        return Result.error("登录失败");
    }
}
